import { StackActions, useNavigation } from '@react-navigation/native';
import React, { useEffect, useState } from 'react';
import { Linking } from 'react-native';
import { BottomDrawerMethods } from 'react-native-animated-bottom-drawer';
import DeviceInfo from 'react-native-device-info';
import { getAvailablePurchases } from 'react-native-iap';
import Toast from 'react-native-toast-message';
import { useDispatch, useSelector } from 'react-redux';

import {
  ACCESS_TOKEN,
  ACCESS_TOKEN_EXPIRE_TIME,
  EULAUrl,
  REFRESH_TOKEN,
  REFRESH_TOKEN_EXPIRE_TIME,
  USER_ID,
  USER_MEMBER_INFO,
} from '@constants/index';
import Clipboard from '@react-native-clipboard/clipboard';

import { clearStorageAllItems, getStorageItem, removeStorageItem } from '../../../utils/storage';
import { paymentAPI } from '@/api/paymentAPI';
import { userAPI } from '@/api/userAPI';
import { clearAll } from '@/stores/slice/userSlice';
import { RootState } from '@/stores/store';
import { getCurrentState } from '@/utils';
import { FirebaseEventsUtil } from '@/utils/analytics';
import { ShareSingleton } from '@/utils/share';

const useSetting = () => {
  const share = ShareSingleton.getInstance();
  // 账号安全选项弹窗
  const accountDrawerRef = React.useRef<BottomDrawerMethods>(null);
  // 关于选择弹框
  const aboutDrawerRef = React.useRef<BottomDrawerMethods>(null);

  // 导航
  const navigation = useNavigation();
  // 展示删除账号的dialog
  const [deleteAccountDialogVisible, setDeleteAccountDialogVisible] = React.useState(false);
  // 用户基本信息
  const [userInfo, setUserInfo] = React.useState<User.UserBaseInfo>();
  // app版本信息
  const [appVersion, setAppVersion] = React.useState<string>('');
  const dispatch = useDispatch();
  const userID = useSelector((state: RootState) => state.user.userId);

  // 点击返回按钮
  const handleBack = () => {
    try {
      // 这里返回不了上一页，暂时用这种方式返回
      if (navigation.canGoBack()) {
        navigation.goBack();
      } else {
        navigation.navigate('User' as never);
      }
    } catch (error) {
      console.log('go back error', error);
      // 跳转到个人页
      navigation.navigate('User' as never);
    }
  };

  // 点击账号安全选项
  const handlePrivacy = () => {
    if (accountDrawerRef.current) {
      accountDrawerRef.current.open();
    }
  };

  // 关闭账号安全选项弹窗
  const handleCloseAccountDrawer = () => {
    if (accountDrawerRef.current) {
      accountDrawerRef.current.close();
    }
  };
  // 点击注销账户按钮
  const handleDeleteAccount = () => {
    setDeleteAccountDialogVisible(true);
  };

  // 点击关于选项
  const handleAbout = () => {
    if (aboutDrawerRef.current) {
      aboutDrawerRef.current.open();
    }
  };
  // 关闭关于弹窗
  const handleCloseAboutDrawer = () => {
    if (aboutDrawerRef.current) {
      aboutDrawerRef.current.close();
    }
  };

  const handleReferralCode = () => {
    navigation.dispatch(StackActions.push('ReferralCode'));
  };

  const handlePro = () => {
    const state = navigation.getState();
    if (state) {
      const name = getCurrentState(state).name;
      FirebaseEventsUtil.goto_subscription(name ?? '');
    }
    navigation.dispatch(StackActions.push('Subscription'));
  };

  const handleReferAndEarn = () => {
    navigation.dispatch(StackActions.push('InviteCode'));
  };

  // 点击登录退出
  const handleLogout = () => {
    console.log('logout');
    try {
      // 清除用户信息（本地）
      removeStorageItem(USER_ID);
      // dispatch(clearUserId());
      // 关闭websocket
      // const wsInstance = WebSocketSingleton.getInstance();
      // wsInstance.close();
      removeStorageItem(ACCESS_TOKEN);
      removeStorageItem(ACCESS_TOKEN_EXPIRE_TIME);
      removeStorageItem(REFRESH_TOKEN);
      removeStorageItem(REFRESH_TOKEN_EXPIRE_TIME);
      removeStorageItem(USER_MEMBER_INFO);
      // 关闭websocket

      // 跳转到登录页
      // navigation.navigate('Login' as never)
    } catch (error) {
      console.log('logout error', error);
    }
  };

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const userId = getStorageItem(USER_ID);
      if (userId) {
        const res = await userAPI.get_user_info(userId);
        setUserInfo(res.data);
      }
    } catch (error) {
      console.log('get user info error', error);
    }
  };
  // 取消删除账号dialog
  const handleCancelDeleteAccount = () => {
    setDeleteAccountDialogVisible(false);
  };
  // 确认删除账号
  const handleConfirmDeleteAccount = async () => {
    try {
      console.log('handleConfirmDeleteAccount : delete user');
      await userAPI.delete_user();
      // 清除用户信息（本地）
      removeStorageItem(USER_ID);
      // dispatch(clearUserId());
      removeStorageItem(ACCESS_TOKEN);
      removeStorageItem(ACCESS_TOKEN_EXPIRE_TIME);
      removeStorageItem(REFRESH_TOKEN);
      removeStorageItem(REFRESH_TOKEN_EXPIRE_TIME);
      removeStorageItem(USER_MEMBER_INFO);
      handleCloseAccountDrawer();
      setDeleteAccountDialogVisible(false);
      clearStorageAllItems();
      // 跳转到欢迎页
      // navigation.dispatch(StackActions.replace('Login'));
      dispatch(clearAll());
      return;
    } catch (error) {
      console.log('delete user error', error);
      Toast.show({
        type: 'tips',
        text1: 'delete user error, try again',
      });
    }
  };
  // 获取app版本信息
  const getAppVersion = () => {
    const version = DeviceInfo.getVersion();
    setAppVersion(`V${version}`);
  };

  // 点击恢复购买记录
  const handleRecoveryPurchaseRecord = async () => {
    try {
      const purchases = await getAvailablePurchases();
      const transactionIdList = purchases.sort((a, b) => b.transactionDate - a.transactionDate);
      await paymentAPI.restoreSubscription(transactionIdList[0].transactionReceipt);
      handleCloseAboutDrawer();
      Toast.show({
        type: 'tips',
        text1: 'Restore Successful',
        props: {
          _type: 'success',
        },
      });
    } catch (error) {
      console.warn(error);
      handleCloseAboutDrawer();

      Toast.show({
        type: 'tips',
        text1: 'Restore Failed',
        props: {
          _type: 'error',
        },
      });
    }
  };

  const handleCopyUserID = () => {
    Clipboard.setString(userID ?? '');
    Toast.show({
      type: 'tips',
      text1: 'Copy Success',
      props: {
        _type: 'success',
      },
    });
  };

  const handleShare = async () => {
    share.realToShare();
  };

  const handleEULA = () => {
    Linking.openURL(EULAUrl);
  };

  useEffect(() => {
    getUserInfo();
    getAppVersion();
  }, []);
  return {
    userID,
    handleBack,
    handlePrivacy,
    accountDrawerRef,
    handleCloseAccountDrawer,
    handleDeleteAccount,
    deleteAccountDialogVisible,
    setDeleteAccountDialogVisible,
    aboutDrawerRef,
    handleAbout,
    handleCloseAboutDrawer,
    handleLogout,
    userInfo,
    handleCancelDeleteAccount,
    handleConfirmDeleteAccount,
    handleRecoveryPurchaseRecord,
    appVersion,
    handleReferralCode,
    handlePro,
    handleReferAndEarn,
    handleCopyUserID,
    handleShare,
    handleEULA,
  };
};

export const useAppSettings = () => {
  const [isDarkMode, setIsDarkMode] = useState(false);
  const [currentLanguage, setCurrentLanguage] = useState('English (US)');

  const toggleDarkMode = () => {
    setIsDarkMode((previousState) => !previousState);
    // Additional logic to apply dark mode to the app
  };

  const changeLanguage = (language: string) => {
    setCurrentLanguage(language);
    // Additional logic to change the app language
  };

  return {
    isDarkMode,
    toggleDarkMode,
    currentLanguage,
    changeLanguage,
  };
};

export default useSetting;
